import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_project/module/provider_test_page/xf_provider/xf_inherited_provider.dart';
import 'package:flutter_test_project/module/provider_test_page/xf_provider/xf_change_notifier.dart';

class XFChangeNotifierProvider<T extends XFChangeNotifier> extends StatefulWidget {
  final Widget child;
  final T data;

  XFChangeNotifierProvider({
    Key key,
    this.data,
    this.child,
  });

  static T of<T>(BuildContext context) {
    final provider = context.dependOnInheritedWidgetOfExactType<XFInheritedProvider<T>>();
    return provider?.data;
  }

  @override
  State createState() => _XFChangeNotifierProviderState();
}

class _XFChangeNotifierProviderState<T extends XFChangeNotifier> extends State<XFChangeNotifierProvider> {
  void update(){
    setState(() =>{});
  }

  @override
  void didUpdateWidget(XFChangeNotifierProvider<T> oldWidget) {
    if (widget.data != oldWidget.data) {
      oldWidget.data.removeListener(update);
      widget.data.addListener(update);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    widget.data.addListener(update);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return XFInheritedProvider<T>(
      data: widget.data,
      child: widget.child,
    );
  }

  @override
  void dispose() {
    widget.data.removeListener(update);
    super.dispose();
  }

}
